"""
数据层
"""
import os
import pickle

from conf import settings


# 保存数据
def save_data(obj):
    # 以类名作为文件夹保存对象
    class_name = obj.__class__.__name__
    user_dir_path = os.path.join(
        settings.DB_PATH,
        class_name
    )
    # 不存在则创建文件夹
    if not os.path.exists(user_dir_path):
        os.mkdir(user_dir_path)

    # 拼接文件名
    user_path = os.path.join(
        user_dir_path,
        obj.username
    )

    # 保存数据
    with open(user_path, mode='wb') as f:
        pickle.dump(obj, f)


# 查询数据
def select_data(cls, username):
    # 以类名作为文件夹保存对象
    class_name = cls.__name__
    user_dir_path = os.path.join(
        settings.DB_PATH,
        class_name
    )
    # 不存在则创建文件夹
    if not os.path.exists(user_dir_path):
        os.mkdir(user_dir_path)

    # 拼接文件名
    user_path = os.path.join(
        user_dir_path,
        username
    )
    # 判读用户是否存在
    if not os.path.exists(user_path):
        return None

    # 返回对象
    with open(user_path, mode='rb') as f:
        return pickle.load(f)
